package com.lqq.controller;

import com.google.common.util.concurrent.RateLimiter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;

/**
 * 限流的控制器
 * @author lqq
 */
@RestController
@Api(value = "限流控制器" +
        "")
@RequestMapping("/rate-limit")
public class RateLimitController {


    private static final RateLimiter ratelimiter = RateLimiter.create(0.5);

    @RequestMapping({"/repeat"})
    @ApiOperation(value = "repeat",httpMethod = "GET")
    public String repeat() {
        boolean getToken = ratelimiter.tryAcquire();
        if(!getToken){
            return "已经被限流";
        }
        return "拿到token";
    }



    @RequestMapping({"/repeat-with-expire-time"})
    @ApiOperation(value = "repeat-with-expire-time",httpMethod = "GET")
    public String repeatWithExpireTime() {
        //等待10秒也要拿到token
        boolean getToken = ratelimiter.tryAcquire(1, 10, TimeUnit.SECONDS);
        if(!getToken){
            return "已经被限流";
        }
        return "拿到token";
    }




}
